package com.xh.core.listener;

import com.google.common.io.Files;
import com.xh.core.event.ConvertFileEvent;
import com.xh.core.properties.XhProperties;
import com.xh.core.util.FileUtils;
import com.xh.core.util.OfficeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/*
 * @Author daiwei
 * @Description
 * @Date 2018/8/13 07:21
 **/
@Component
public class ConvertFileListner {

    @Autowired
    private XhProperties xhProperties;

    @EventListener
    @Async
    public void convert(ConvertFileEvent convertFileEvent){
        if(!xhProperties.getUpload().getAutoConvert()){
            return;
        }
        String ext="."+ Files.getFileExtension(convertFileEvent.getSourceUrl());
        ext=ext.toLowerCase();
        if(".doc;.docx;.xls;.xlsx;.ppt;.pptx".indexOf(ext)>=0) {
            String pdfPath= FileUtils.changeExt(convertFileEvent.getSourceUrl(), "pdf");

            if(".doc;.docx".indexOf(ext)>=0) {
                OfficeUtils.word2pdf(convertFileEvent.getSourceUrl(),pdfPath,null);
            }else if(".xls;.xlsx".indexOf(ext)>=0) {
                OfficeUtils.excel2pdf(convertFileEvent.getSourceUrl(),pdfPath,null);
            }else if(".ppt;.pptx".indexOf(ext)>=0) {
                OfficeUtils.ppt2pdf(convertFileEvent.getSourceUrl(),pdfPath);
            }
        }
    }
}
